package person.learn.messageconverter;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Created by barton on 16-5-26.
 */
public class JsonFormatHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
    public JsonFormatHttpMessageConverter() {
        super(new MediaType("application", "*+json", Charset.forName("UTF-8")));
//        super(new MediaType("application", "x-sanji", Charset.forName("UTF-8")));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return Object.class.isAssignableFrom(clazz);
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws
            IOException, HttpMessageNotReadableException {

        return inputMessage.getBody();
    }

    @Override
    protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException,
            HttpMessageNotWritableException {
        if (null != o) {
            outputMessage.getBody().write(o.toString().getBytes());
            return;
        }
        outputMessage.getBody().write("".getBytes());
    }


}
